<!-- 供给计量 -->
<template>
  <div class="supply-meter">
    <div class="tabs">
      <px-radio-group v-model="activeName" class="tabSwitch" @change="tabSelectHandler">
        <px-radio-button v-for="item in tabsOption" :key="item.name" :label="item.name">{{ item.label }}</px-radio-button>
      </px-radio-group>
      <div class="top_query">
        <px-form ref="queryRef" class="custom-form-ui inspection-form" :model="queryParams" :inline="true" label-width="100px">
          <px-form-item label="时间维度" prop="dataFormat" style="width: auto; padding-right: 10px">
            <px-radio-group v-model="timeStr" style="margin-left: 10px" @change="handleChangeFn">
              <px-radio v-if="activeName === 'overView'" size="small" label="Hourly">小时</px-radio>
              <px-radio size="small" label="Daily">日</px-radio>
              <px-radio size="small" label="Monthly">月</px-radio>
              <px-radio size="small" label="Yearly">年</px-radio>
            </px-radio-group>
          </px-form-item>
          <px-form-item label="时间范围" style="width: 430px">
            <px-date-picker
              v-if="timeStr === 'Hourly'"
              v-model="dateRange"
              type="datetimerange"
              range-separator="-"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :defaultTime="defaultTime"
            />
            <px-date-picker
              v-if="timeStr === 'Daily'"
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
            <px-date-picker
              v-if="timeStr === 'Monthly'"
              v-model="dateRange"
              type="monthrange"
              value-format="YYYY-MM"
              range-separator="-"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
            />
            <div v-if="timeStr === 'Yearly'">
              <yearPicker ref="statisticPicker" :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
            </div>
          </px-form-item>
          <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
          <px-button icon="" @click="resetQuery">重置</px-button>
          <px-button v-has="'ALL_ENERGY_SUPPLY_OVERVIEW_DOWNLOAD'" @click="handleExport">导出</px-button>
        </px-form>
      </div>
    </div>
    <!-- <div ref="switchTabsContentRef"> -->
    <transition name="fab-tabs-fade" mode="out-in">
      <keep-alive>
        <component :is="activeCom" :key="comKey" :activeName="activeName" :params="queryParams" class="componnet_com" />
      </keep-alive>
    </transition>
    <!-- </div> -->
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_ENERGY_SUPPLY_OVERVIEW"
});

import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import overViewCom from "./overView/index.vue";
import electicityCom from "./electricity/index.vue";
import waterCom from "./water/index.vue";
// import dieselCom from "./Diesel/index.vue";
import gasCom from "./Gas/index.vue";
import ngCom from "./NG/index.vue";
import streamHotwaterCom from "./streamHotwater/index.vue";
import { ref, markRaw, computed, onMounted, onUnmounted, getCurrentInstance } from "vue";
import { type OptionsType } from "@/components/ReSegmented";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";

import { PxMessage } from "px-ui";

import dayjs from "dayjs";

const defaultHeight = ref<number>(700);

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const comKey = ref(Date.now());

const { proxy }: any = getCurrentInstance();

const timeStr = ref("Monthly");

const tabsOption = ref<Array<OptionsType>>([
  {
    name: "overView",
    label: "总览",
    com: markRaw(overViewCom)
  },
  {
    name: "Electricity",
    label: "电",
    com: markRaw(electicityCom)
  },
  {
    name: "Water",
    label: "水",
    com: markRaw(waterCom)
  },
  {
    name: "NG",
    label: "天然气",
    com: markRaw(ngCom)
  },
  {
    name: "HotStream",
    label: "蒸汽/热水",
    com: markRaw(streamHotwaterCom)
  },
  {
    name: "Gas",
    label: "大宗气",
    com: markRaw(gasCom)
  }
  // {
  //   name: "Diesel",
  //   label: "柴油",
  //   com: markRaw(dieselCom)
  // }
]);

const yearStart = ref("");
const yearEnd = ref("");
// 可选择区间，initYear传参，不传则所有年份有效，小于0判断一下？
const dateValue = ref<any>({ startYear: new Date().getFullYear() - 2, endYear: new Date().getFullYear() });
// 选完/输入完成的回调
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  dateRange.value = [startYear ? startYear.toString() : "", endYear ? endYear.toString() : ""];
  yearStart.value = `${startYear}-01-01 00:00:00`;
  yearEnd.value = `${endYear}-12-31 23:59:59`;
};

// 定义数据
const dateRange = ref<any>([]);

interface queryForm {
  queryTimeGranularity?: string;
  level?: string;
  factory?: string;
  startTime?: string;
  endTime?: string;
}

const queryParams = ref<queryForm>({
  queryTimeGranularity: "Daily",
  factory: localStorage.getItem("facCode") || ""
});

const activeName = ref("overView");

const switchTabsContentRef = ref(null);

const activeCom = computed(() => tabsOption.value.find(item => item.name === activeName.value).com);
const switchTabsChangeHandler = async () => await useUpdateDomHeight(defaultHeight, switchTabsContentRef, null, defaultHeight.value);

const tabSelectHandler = async (selectName: string) => {
  activeName.value = selectName;
  if (selectName !== "overView" && timeStr.value === "Hourly") {
    timeStr.value = "Daily";
    handleChangeFn(timeStr.value);
  } else {
    handleQuery();
  }
  await switchTabsChangeHandler();
};

// 获取当月第一天
const getCurrentMonthF = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d = "01";
  m = m < 10 ? "0" + m : m;
  return [y, m, d].join("-");
};

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d: any = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

const handleChangeFn = (val: string) => {
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  switch (val) {
    case "Hourly":
      dateRange.value = [`${year}-${month}-${da} 00:00:00`, `${year}-${month}-${da} 23:59:59`];
      break;
    case "Daily":
      dateRange.value = [getCurrentMonthF(), getCurrentMonthL()];
      break;
    case "Monthly":
      dateRange.value = [`${year}-01`, `${year}-12`];
      break;
    case "Yearly":
      let yearS = new Date().getFullYear() - 2;
      let yearE = new Date().getFullYear();
      yearStart.value = `${yearS}-01-01 00:00:00`;
      yearEnd.value = `${yearE}-12-31 23:59:59`;
      break;
    default:
      break;
  }
  console.log(dateRange.value, val, "123213213213");
  handleQuery();
};

// 校验时间范围不为空
const checkDate = () => {
  if (queryParams.value.queryTimeGranularity) {
    if (dateRange.value && dateRange.value.length) {
      return true;
    }
    if (queryParams.value.startTime && queryParams.value.endTime) {
      return true;
    }
  }
};

// 获取某月最后一天
const getMonthLastDay = (y, m) => {
  let date = new Date(y, m - 1, "01");
  date.setDate(1);
  date.setMonth(date.getMonth() + 1);
  let cdate = new Date(date.getTime() - 1000 * 60 * 60 * 24);
  return cdate.getDate();
};

const timeType = ref("Monthly");
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.queryTimeGranularity = timeStr.value;
  timeType.value = timeStr.value;
  console.log(queryParams.value.startTime, queryParams.value.endTime, "******************");
  if (queryParams.value.queryTimeGranularity === "Daily") {
    queryParams.value.startTime = dateRange.value[0] + " 00:00:00";
    queryParams.value.endTime = dateRange.value[1] + " 23:59:59";
  } else if (queryParams.value.queryTimeGranularity === "Monthly") {
    queryParams.value.startTime = dateRange.value[0].indexOf("00") != -1 ? dateRange.value[0] : dateRange.value[0] + "-01 00:00:00";
    const d = getMonthLastDay(Number(dateRange.value[1].split("-")[0]), Number(dateRange.value[1].split("-")[1]));
    queryParams.value.endTime = dateRange.value[1].indexOf("59") != -1 ? dateRange.value[1] : dateRange.value[1] + "-" + d + " 23:59:59";
  } else if (queryParams.value.queryTimeGranularity === "Hourly") {
    queryParams.value.startTime = dateRange.value[0];
    queryParams.value.endTime = dateRange.value[1];
  } else {
    queryParams.value.startTime = yearStart.value;
    queryParams.value.endTime = yearEnd.value;
  }
  console.log(queryParams.value.startTime, queryParams.value.endTime);
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) return;
    if (timeStr.value) {
      if (!checkDate()) {
        return PxMessage({
          type: "warning",
          message: "时间范围不能为空"
        });
      }
    }
  });
  comKey.value = Date.now();
}
/** 重置按钮操作 */
function resetQuery() {
  initQuery();
  comKey.value = Date.now();
}

// 默认查询条件
const initQuery = () => {
  // timeStr.value = "Daily";
  // //获取新的时间
  // let date = new Date();
  // //获取当前时间的年份转为字符串
  // let year = date.getFullYear().toString();
  // //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  // let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  // //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  // let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  // let y = date.getFullYear(); // 获取年
  // let m: any = date.getMonth() + 1; // 获取月
  // queryParams.value.queryTimeGranularity = timeStr.value;
  // timeType.value = timeStr.value;
  // // dateRange.value = [`${year}-${month}`, `${year}-${month}`];
  // dateRange.value = [getCurrentMonthF(), getCurrentMonthL()];
  // queryParams.value.startTime = getCurrentMonthF() + " 00:00:00";
  // queryParams.value.endTime = getCurrentMonthL() + " 23:59:59";
  timeStr.value = "Monthly";
  queryParams.value.queryTimeGranularity = "Monthly";
  timeType.value = "Monthly";
  dateRange.value = [dayjs().subtract(12, "month").format("YYYY-MM"), dayjs().subtract(1, "month").format("YYYY-MM")];
  queryParams.value.startTime = dayjs().subtract(12, "month").format("YYYY-MM") + "-01 00:00:00";
  queryParams.value.endTime = dayjs().subtract(1, "month").endOf("month").format("YYYY-MM-DD") + " 23:59:59";
};

// 导出
const handleExport = () => {
  const dimensionMap = {
    Hourly: "Hour",
    Daily: "Day",
    Monthly: "Month",
    Yearly: "Year"
  };
  const params = {
    dimension: dimensionMap[queryParams.value.queryTimeGranularity],
    startDate: queryParams.value.startTime,
    endDate: queryParams.value.endTime,
    level: queryParams.value.factory
  };
  if (activeName.value === "overView") {
    proxy.download("post", "/energy/supplyMeasure/exportSummary", params, "供给计量-总览.xlsx");
  }
  if (activeName.value === "Electricity") {
    proxy.download("post", "/energy/supplyMeasure/exportElectricity", params, "供给计量-电.xlsx");
  }
  if (activeName.value === "Water") {
    proxy.download("post", "/energy/supplyMeasure/exportWater", params, "供给计量-水.xlsx");
  }
  if (activeName.value === "Gas") {
    proxy.download("post", "/energy/supplyMeasure/exportGas", params, "供给计量-大宗气.xlsx");
  }
  if (activeName.value === "HotStream") {
    proxy.download("post", "/energy/supplyMeasure/exportHotSteam", params, "供给计量-蒸汽/热水.xlsx");
  }
  if (activeName.value === "NG") {
    proxy.download("post", "/energy/supplyMeasure/exportNg", params, "供给计量-天然气.xlsx");
  }
};

onMounted(async () => {
  await switchTabsChangeHandler();
  initQuery();
  handleQuery();
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<style lang="scss" scoped>
.supply-meter {
  display: flex;
  flex-direction: column;

  .tabs {
    display: flex;
    align-items: center;
    height: 76px;
    padding: 16px 24px;
    margin-bottom: 16px;
    background: #fff;

    /*
    * tab样式
    */
    .tabSwitch {
      min-width: 300px;
      height: 44px;
      padding: 0 5px;
      margin-right: 20px;
      background-color: #f4f4f4;
      border-radius: 4px;

      :deep(.px-radio-button__inner) {
        background-color: #f4f4f4;
        border: none;
      }

      :deep(.is-active) {
        border: none;

        .px-radio-button__inner {
          background-color: var(--px-color-primary);
          border-radius: 4px;
        }
      }
    }
  }

  .px-form-item {
    margin-bottom: 0;
  }
}
</style>
